import { PlusOutlined } from '@ant-design/icons';
import { Button, Card, Col, Form, message, Row } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import { stringify } from 'qs';
import React, { PureComponent } from 'react';
import router from 'umi/router';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import { getToken } from '../../../components/common/PateoForm/utils/helper';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoTable from '../../../components/common/PateoTable';
import IPDADetailModal from '../../../components/ipda/ipdaDetailModal';
import BindingEditModel from '../../../components/simCard/simCardBindingModel';
import SIMDetailModal from '../../../components/simCard/simCardDetailModal';
import TboxDetailModal from '../../../components/Tbox/tboxDetailModel';
import VehicleDetailModal from '../../../components/vehicle/vinDetailModal';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import { getDicByKey, getDictOptionsByCode } from '../../../support/common';
import MaskText from '@/components/MaskText';
import styles from './TableList.less';
import { fingerprintFetch } from '@/utils/request'

const FormItem = Form.Item;
@connect(state => ({
  simCard: state.simCard,
  menu: state.menu,
}))
// @Form.create()
export default class SimCardList extends PureComponent {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.array,
  };
  fromRef = React.createRef();
  CollectionsPageRef = React.createRef();
  state = {
    // bindingEditVisible: false,
    tboxDetailVisible: false,
    vinDetailVisible: false,
    simDetailVisible: false,
    ipdaDetailVisible: false,
    tboxDetailModelData: {},
    vinDetailModelData: {},
    simDetailModelData: {},
    ipdaDetailModelData: {},
    // bindingEditModelData: {},
    selectedRows: [],
    formValues: {},
  };

  componentWillMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'simCard/clearData',
      payload: {},
    });
  }
  componentDidMount() {
    if (this.state.formValues) {
      this.fromRef.current.setFieldsValue({
        deviceId: this.state.formValues.deviceId,
        iccid: this.state.formValues.iccid,
        msisdn: this.state.formValues.msisdn,
      });
    }

    const { dispatch } = this.props;
    dispatch({
      type: 'simCard/fetch',
      payload: {
        // page: pageObj.current - 1,
        // size: pageObj.pageSize,
      },
    });
  }
  handleFormReset = () => {
    const { dispatch } = this.props;
    this.fromRef.current.resetFields();
    this.state.formValues = {};
    dispatch({
      type: 'simCard/fetch',
      payload: {
        // page: pageObj.current - 1,
        // size: pageObj.pageSize,
      },
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'tbox/remove',
          payload: {
            no: selectedRows.map(row => row.no).join(','),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  handleEditDate = deviceId => {
    const { dispatch, simCard: {
      loading,
      list: { list, pagination },
    } } = this.props;

    const obj = {};
    obj.pageObj = pagination;
    obj.values = this.state.formValues;
    dispatch({
      type: 'simCard/findById',
      payload: deviceId,
      callback: data => {
        if (data.statusCode === '0') {
          router.push({
            pathname: '/connectPlat/simCard/simCardEdit',
            flag: true,
            state: { data: data.data, obj },
          });
        } else {
          message.error(data.statusMessage);
        }
      },
    });
  };
  handleBindingDate = record => {
    const { simCard: {
      loading,
      list: { list, pagination },
    } } = this.props;
    const obj = record;
    obj.page = pagination;
    obj.formValues = this.state.formValues;
    this.CollectionsPageRef.current.showModalEdit(obj);
  };
  // 验证deviceId是否存在
  checkUsername = (rule, value, callback) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tbox/checkDeviceId',
      payload: value,
      callback: data => {
        return data ? callback() : callback('tbox设备Id已存在');
      },
    });
  };
  handleSearch = fieldsValue => {
    const { dispatch } = this.props;
    this.setState({
      formValues: fieldsValue,
    });
    dispatch({
      type: 'simCard/fetch',
      payload: fieldsValue,
    });
  };
  handleDetailTbox = deviceId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tbox/fetchtboxdetail',
      payload: deviceId,
      callback: tboxDetail => {
        this.setState({ tboxDetailModelData: tboxDetail.data, tboxDetailVisible: true });
      },
    });
  };
  handleDetailIPDA = deviceId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ipda/findById',
      payload: deviceId,
      callback: ipdaDetail => {
        if (ipdaDetail.data.status.code === '0') {
          this.setState({ ipdaDetailModelData: ipdaDetail.data, ipdaDetailVisible: true });
        } else {
          message.error(ipdaDetail.data.status.description);
        }
      },
    });
  };
  handleDetailSIM = deviceId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'simCard/findById',
      payload: deviceId,
      callback: simDetail => {
        if (simDetail.statusCode === '0') {
          this.setState({ simDetailModelData: simDetail.data, simDetailVisible: true });
        } else {
          message.error(simDetail.statusMessage);
        }
      },
    });
  };
  handleDetailVIN = vin => {
    const { dispatch } = this.props;
    dispatch({
      type: 'vehicle/findProfile',
      payload: vin,
      callback: response => {
        if (response.statusCode === '0') {
          if (response.data) {
            this.setState({ vinDetailModelData: response.data, vinDetailVisible: true });
          }
        } else {
          message.error(response.description);
        }
      },
    });
  };
  handleExportExcel = () => {
    const { formValues } = this.state;
    const {
      simCard: {
        list: { pagination },
      },
    } = this.props;
    const str = `${window.g.url}/simcard/export?${stringify(formValues)}`;
    const newOptions = {};
    newOptions.method = 'GET';
    newOptions.headers = {
      OptAuthorization: `${getToken()}`,
      'Content-Type': 'application/json;charset=utf-8',
    };

    if (pagination.total <= 5000 && pagination.total !== 0) {
      fingerprintFetch(str, newOptions)
        .then(response => {
          if (response.status === 200) {
            return response.blob();
          } else {
            throw response;
          }
        })
        .then(blob => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `SIM卡列表${new Date().toLocaleDateString()}.xls`;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        })
        .catch(() => message.error('导出失败，请稍后在试!'));
    } else {
      message.warning('您目前搜索的结果等于0条或者大于5000条，请选择查询条件，精确查询范围！');
    }
  };
  renderForm() {
    // const { getFieldDecorator } = this.props.form;

    const {
      menu: { dicData, permissions },
      location: { pathname = '/' },
    } = this.props;
    const simStatusOptions = getDictOptionsByCode(this.context.dicData, 'simStatus');
    const carrierBrandOptions = getDictOptionsByCode(this.context.dicData, 'carrierBrand');
    const colStyle = { paddingLeft: 0, paddingTop: 10 };
    const isAuth = permissions.includes('/connectPlat/simCard/simCardAdd/simCardAdd_show');
    const searchItems = [
      // {
      //   title: '品牌',
      //   type: 'select',
      //   // customStyle: 6,
      //   initialValue: 'MATC',
      //   selectOptions: [{ value: 'MATC', label: '猛士科技' }],
      //   key: 'brandId',
      //   rules: [{ required: true, message: '品牌为必选项！' }],
      // },
      {
        title: 'IMSI',
        type: 'input',
        key: 'deviceId',
      },
      {
        title: 'ICCID',
        type: 'input',
        key: 'iccid',
      },
      {
        title: 'SIM卡号',
        type: 'input',
        key: 'msisdn',
      },
      {
        title: '运营商品牌',
        type: 'select',
        selectOptions: carrierBrandOptions,
        key: 'carrierBrand',
      },
      {
        title: '绑定状态',
        type: 'select',
        selectOptions: simStatusOptions,
        key: 'simStatus',
      },
    ];
    return (
      <Card bordered={false}>
        <PateoSearchForm
          searchItems={searchItems}
          onRef={ref => (this.fromRef = ref)}
          fetchParams={{ type: 'simCard/fetch' }}
          saveFormValues={val =>
            this.setState({ formValues: Object.assign(this.state.formValues, val) })
          }
          handleFormReset={() => this.setState({ formValues: {} })}
        />
      </Card>
      // <Form labelCol={{offset: 1}} ref={this.fromRef} onFinish={this.handleSearch} layout="inline" width="100%">
      //   <Row width='100%'>
      //     <Col style={colStyle} span={8}>
      //       <FormItem label="IMSI" name='deviceId' >
      //           <Input placeholder="请输入IMSI" />
      //       </FormItem>
      //     </Col>
      //     <Col style={colStyle} span={8}>
      //       <FormItem label="ICCID" name='iccid'>
      //           <Input placeholder="请输入ICCID" />
      //       </FormItem>
      //     </Col>
      //     <Col style={colStyle} span={8}>
      //       <FormItem label="SIM卡号" name='msisdn'>
      //           <Input placeholder="请输入SIM卡号" />
      //       </FormItem>
      //     </Col>
      //   <Col style={colStyle} span={8}>
      //       <FormItem label="运营商品牌" name='carrierBrand'>
      //         <Select allowClear placeholder="请选择运营商品牌" options={carrierBrandOptions}>
      //         </Select>
      //       </FormItem>
      //     </Col>
      //     <Col style={colStyle} span={8}>
      //       <FormItem label="绑定状态" name='simStatus'>
      //           <Select allowClear placeholder="请选择状态" options={simStatusOptions}>
      //           </Select>
      //       </FormItem>
      //     </Col>
      //     <Col style={colStyle} span={8} >
      //       <Row justify='end'>
      //         <FormItem noStyle><Button type="primary" htmlType="submit">查询</Button></FormItem>
      //         <FormItem noStyle><Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button></FormItem>
      //         {isAuth ? (<Button  style={{ marginLeft: 8 }} icon={(<PlusOutlined />)} type="primary" onClick={() => this.props.history.push('/connectPlat/simCard/simCardAdd')}>新增</Button>) : ''}
      //       </Row>
      //     </Col>
      //   </Row>
      //   {/* <Row>
      //     <Col style={colStyle} span={8}>
      //       {isAuth ? (<Button icon={(<PlusOutlined />)} type="primary" onClick={() => this.props.history.push('/connectPlat/simCard/simCardAdd')}>新增</Button>) : ''}
      //     </Col>
      //   </Row> */}
      // </Form>
    );
  }

  render() {
    const { tbox } = this.state;
    const {
      menu: { dicData, permissions },
      simCard: {
        loading,
        list: { list, pagination },
      },
      dispatch,
      location: { pathname = '/' },
    } = this.props;
    const page = pagination;
    const colStyle = { paddingLeft: 0, paddingBottom: 16 };
    const isAuth = permissions.includes('/connectPlat/simCard/simCardAdd/simCardAdd_show');
    const columns = [
      {
        title: 'IMSI',
        dataIndex: 'deviceId',
        render: text => {
          return <a onClick={() => this.handleDetailSIM(text)}>{text}</a>;
        },
      },
      {
        title: 'ICCID',
        dataIndex: 'iccid',
        render: text => {
          return text;
        },
      },
      {
        title: 'SIM卡号',
        dataIndex: 'msisdn',
        render: text => {
          return <MaskText text={text} type="simCard" />;
        },
      },
      {
        title: '状态',
        dataIndex: 'simStatus',
        render: text => {
          if (text || text === 0) {
            return getDicByKey(this.context.dicData, 'simStatus', text.toString())
              ? getDicByKey(this.context.dicData, 'simStatus', text.toString())
              : text;
          } else {
            return text;
          }
        },
      },
      {
        title: '运营商品牌',
        dataIndex: 'carrierBrand',
        render: text => {
          if (text || text === 0) {
            return getDicByKey(this.context.dicData, 'carrierBrand', text.toString())
              ? getDicByKey(this.context.dicData, 'carrierBrand', text.toString())
              : text;
          } else {
            return text;
          }
        },
      },
      {
        title: 'VIN号',
        dataIndex: 'vin',
        render: text => {
          return <a onClick={() => this.handleDetailVIN(text)}>{text}</a>;
        },
      },
      {
        title: '关联设备ID',
        dataIndex: 'groupDevice',
        render: (text, record) => {
          if (record.deviceType === '2') {
            return <a onClick={() => this.handleDetailTbox(text)}>{text}</a>;
          } else {
            return <a onClick={() => this.handleDetailIPDA(text)}>{text}</a>;
          }
        },
      },
      {
        title: '关联设备类型',
        dataIndex: 'deviceType',
        render: text => {
          return getDicByKey(this.context.dicData, 'deviceType', text);
        },
      },
      {
        title: '入库时间',
        dataIndex: 'createDate',
        render: text => {
          return text;
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 200,
        fixed: 'right',
        render: (text, record) => {
          const editBtn = {
            title: '编辑',
            key: 'edit',
            auth: 'simCard-opt',
            onConfirm: () => this.handleEditDate.bind(this)(record.deviceId),
          };
          const bindBtn = {
            title: '修改绑定关系',
            key: 'editBinding',
            auth: 'simCard-opt',
            onConfirm: () => this.handleBindingDate.bind(this)(record),
          };
          const btns = [];
          btns.push(editBtn);
          if (!(record && record.projectId && record.projectId === 'dfspt')) {
            btns.push(bindBtn);
          }
          return <PateoAuthButtons pathname={pathname} authStr="simCard-opt" btns={btns} />;
        },
      },
    ];

    // const paginationProps = {
    //   showSizeChanger: true,
    //   showQuickJumper: true,
    //   ...pagination,
    //   showTotal: () => <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>,
    // };
    const paginationProps = {
      pageSizeOptions: [10, 20, 50],
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    // const tableProps = {
    //   columns, // 列
    //   rowKey: record => record.sid, // key
    //   loading, // 控制加载
    //   // bordered: true, // 边框
    //   selectedRows: [],
    //   dataSource: list, // 远程数据
    //   pagination: paginationProps, // 分页
    //   scroll: { x: '150%' },
    // };
    const tableProps = {
      columns,
      dataSource: this.props.simCard.list.list,
      loading,
      rowKey: record => record.sid,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    return (
      <PageHeaderLayout>
        {/* <Card bordered={false}> */}
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <Card style={{ marginTop: 12 }}>
            <Row>
              <Col style={colStyle} span={24}>
                {isAuth ? (
                  <Button
                    icon={<PlusOutlined />}
                    type="primary"
                    size="small"
                    onClick={() => this.props.history.push('/connectPlat/simCard/simCardAdd')}
                  >
                    新增
                  </Button>
                ) : (
                  ''
                )}
              </Col>
            </Row>
            <PateoTable
              tableProps={tableProps}
              dispatch={dispatch}
              fetchParams={{ type: 'simCard/fetch' }}
              formValues={this.state.formValues}
            />
          </Card>
          <TboxDetailModal
            changeVisible={() =>
              this.setState({ tboxDetailVisible: false, tboxDetailModelData: {} })
            }
            visible={this.state.tboxDetailVisible}
            detailModelData={this.state.tboxDetailModelData}
            dispatch={dispatch}
          />
          <SIMDetailModal
            changeVisible={() => this.setState({ simDetailVisible: false, simDetailModelData: {} })}
            visible={this.state.simDetailVisible}
            detailModelData={this.state.simDetailModelData}
            dispatch={dispatch}
          />
          <IPDADetailModal
            changeVisible={() =>
              this.setState({ ipdaDetailVisible: false, ipdaDetailModelData: {} })
            }
            visible={this.state.ipdaDetailVisible}
            detailModelData={this.state.ipdaDetailModelData}
            dispatch={dispatch}
          />
          <VehicleDetailModal
            changeVisible={() => this.setState({ vinDetailVisible: false, vinDetailModelData: {} })}
            visible={this.state.vinDetailVisible}
            detailModelData={this.state.vinDetailModelData}
            dispatch={dispatch}
          />
          <BindingEditModel
            ref={this.CollectionsPageRef}
            icon="plus"
            type="primary"
            title="修改绑定关系"
            dispatch={this.props.dispatch}
            tbox={tbox}
            resetOutterForm={this.handleFormReset}
          />
        </div>
        {/* </Card> */}
      </PageHeaderLayout>
    );
  }
}
